var db = require('./db'), 
utils = require('./utils'),
async = require('async');

function getjson(request, response, render) {
    async.waterfall(
        [
            async.apply(db.findFeedsByKeys, request.user.keys)
        ],
        function(error, feeds) {
            if (error) {
                render(request, response, result);
                return;
            }

            var result = {
                'title': 'My Speech',
                'link': 'null',
                'episodes': []
            };

            var episodes = [];
            for (var i=0; i<feeds.length; i++) {
                var ep = {
                    'title': feeds[i].title,
                    'link': feeds[i].link,
                   	'summary': feeds[i].summary,
                    'pubdate': feeds[i].pubDate,
                    'key': feeds[i].key,
                };
                episodes.push(ep);
            }

            async.waterfall(
                [
                    utils.addSpeechLinks(request, episodes),
                    function(eps, cb) {
                        result.episodes = eps;
                        render(request, response, result);
                        cb(null);
                    }
                ]
            );
        }
    );
}

module.exports = {
  getjson: getjson
}
